package com.three.utils;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.three.constant.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Reader;
import java.lang.reflect.Type;

/**
 * @Author mathua
 * @Date 2017/5/19 16:39
 */
public final class JsonUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtils.class);
    private static Gson gson = new Gson();

    public static String toJson(Object bean) {
        try {
            return gson.toJson(bean);
        } catch (Exception e) {
            LOGGER.error("Jsons.toJson ex, bean=" + bean, e);
        }
        return null;
    }

    public static <T> T fromJson(String json, Class<T> clazz) {

        try {
            return gson.fromJson(json, clazz);
        } catch (Exception e) {
            LOGGER.error("Jsons.fromJson ex, json=" + json + ", clazz=" + clazz, e);
        }
        return null;
    }

    public static <T> T fromJson(byte[] json, Class<T> clazz) {
        return fromJson(new String(json, Constants.UTF_8), clazz);
    }

    public static <T> T fromJson(String json, Type type) {
        try {
            return gson.fromJson(json, type);
        } catch (Exception e) {
            LOGGER.error("Jsons.fromJson ex, json=" + json + ", type=" + type, e);
        }
        return null;
    }

    public static <T> T jsonToBean(Reader json, Class<T> classOfT) {
        try {
            return gson.fromJson(json, classOfT);
        } catch (JsonSyntaxException e) {
            return null;
        }
    }

}